﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Things.OrderPlan.Models;

namespace Things.OrderPlan
{
    public class SaleSetRepository
    {
        public bool Restore(SaleSet set)
        {
            using (Models.ModelsContainer container = new ModelsContainer())
            {
                if (container.SaleSetSet
                    .Where(p => p.Id == set.Id)
                    .Select(p => p.Id ).SingleOrDefault() != default(Guid))
                {
                    container.SaleSetSet.Attach(set);
                    container.ObjectStateManager.ChangeObjectState(set, System.Data.EntityState.Modified);
                }
                else
                {
                    container.SaleSetSet.AddObject(set);
                }
                if(container.SaveChanges()>0)
                {
                    return true;
                }
            }
            return false;
        }

        public bool Delete(SaleSet set)
        {
            using (Models.ModelsContainer container = new ModelsContainer())
            {
                container.SaleSetSet.DeleteObject(set);
                if (container.SaveChanges() > 0)
                {
                    return true;
                }
            }
            return false;
        }

        public SaleSet Find(Guid setId)
        {
            using (Models.ModelsContainer container = new ModelsContainer())
            {
                return container.SaleSetSet.Where(p => p.Id == setId).FirstOrDefault<SaleSet>();
            }
        }

        public List<SaleSet> FindAll(Guid goodsId)
        {
            using (Models.ModelsContainer container = new ModelsContainer())
            {
                return container.SaleSetSet.Where(p => p.GoodsId == goodsId).ToList<SaleSet>();
            }
        }

        public SaleSet Find(Guid goodsId, string type)
        {
            using (Models.ModelsContainer container = new ModelsContainer())
            {
                return container.SaleSetSet.Where(p => p.GoodsId == goodsId
                    && p.Description == type.ToUpper())
                    .SingleOrDefault();
            }
        }
    }
}
